package com.lili.backtrack;

import java.util.*;

/**
 * @Auther: 李 力
 * @Date: 2024/8/20
 * @Description: 全排列II
 * @version: 1.0
 */
public class LeetCode47 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        dfs(nums, new boolean[nums.length], new LinkedList<>(), result);
        return result;
    }

    private static void dfs(int[] nums, boolean[] b, LinkedList<Integer> stack, List<List<Integer>> result) {
        if (stack.size() == nums.length) {
            result.add(new ArrayList<>(stack));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (i != 0 && nums[i] == nums[i - 1] && !b[i - 1]) {
                continue;
            }
            if (!b[i]) {
                stack.push(nums[i]);
                b[i] = true;
                dfs(nums, b, stack, result);
                b[i] = false;
                stack.poll();
            }
        }
    }
}
